package com.coding4play.mqtt.store.util;

import cn.hutool.core.util.StrUtil;

import java.util.List;

public class StringTopicMatch {


    /**
     * @param topic
     * @param topicFilter
     * @return
     */
    public static Boolean match(String topic, String topicFilter) {
        List<String> splitTopics = StrUtil.split(topic, '/');
        List<String> splitTopicFilters = StrUtil.split(topicFilter, '/');
        int size = splitTopicFilters.size();
        if (splitTopics.size() >= size) {
            String newTopicFilter = "";
            for (int i = 0; i < size; i++) {
                String value = splitTopicFilters.get(i);
                if (value.equals("+")) {
                    newTopicFilter = newTopicFilter + "+/";
                } else if (value.equals("#")) {
                    newTopicFilter = newTopicFilter + "#/";
                    break;
                } else {
                    newTopicFilter = newTopicFilter + splitTopics.get(i) + "/";
                }
            }
            newTopicFilter = StrUtil.removeSuffix(newTopicFilter, "/");
            return topicFilter.equals(newTopicFilter);
        }

        return false;
    }

    public static void main(String[] args) {
        System.out.println(match("device/bms", "device/#"));
    }
}
